package com.suncnpap.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.database.mybatis.Page;
import com.suncnpap.base.common.ParamModel;
import com.suncnpap.base.controller.BaseController;
import com.suncnpap.system.model.Menu;
import com.suncnpap.system.service.MenuRoleService;
import com.suncnpap.system.service.MenuService;

@Controller
@RequestMapping(value="/system/menuInit")
public class MenuInitController extends BaseController{
	
	@Autowired
	MenuService menuService;
	
	@Autowired
	MenuRoleService menuRoleService;
	
	@RequestMapping(value="/list")
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
	
		HandlerResult result = this.checkToken(request);
		
		if (result.getCode()==0) {

			Page page = this.setPage();
			page.removeQueryAnd("strSchoolId");
			
			String strState = this.getParameter("strState", "");
			if(!strState.equals("")){
				page.addQueryAnd("strState", strState);
			}
			
			List<Menu> menuList = menuService.getList(page, "");
			
			
			Map<String, List<Menu>> menuMap = ObjUtil.listToMapByField(menuList, "strParentId");
			menuList = creatMenuTree(menuList, menuMap);
			List<Map<String,Object>> objList = new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> childrenList = new ArrayList<Map<String,Object>>();
			
			if(menuList!=null && menuList.size()>0){
				for(Menu obj:menuList){
					if(obj.getStrParentId().equals("-1")){
						Map<String,Object> temp = new HashMap<String,Object>();
						temp.put("strParentNodeId", obj.getStrId());
						temp.put("strParentNodeName", obj.getStrName());
						temp.put("strTitle", obj.getStrTitle());
						temp.put("strIcon", obj.getStrIcon());
						temp.put("strRoute", obj.getStrRoute());
						temp.put("strUrl", obj.getStrUrl());
						temp.put("dtCreatDate", obj.getDtCreatDate());
						temp.put("dtUpdateDate", obj.getDtUpdateDate());
						temp.put("strState", obj.getStrState());
						List<Map<String,Object>> tempJson = creatJsonTree(obj.getChildren());
						if(tempJson!=null && tempJson.size()>0){
							temp.put("children", tempJson);
						}
						temp.put("expand", false);
						childrenList.add(temp);
					}
				}
				
			}
			Map<String,Object> tempMap = new HashMap<String,Object>();
			tempMap.put("strParentNodeId", "-1");
			tempMap.put("strParentNodeName", "菜单列表");
			if(childrenList!=null && childrenList.size()>0){
				tempMap.put("children", childrenList);
			}
			tempMap.put("expand", true);
			objList.add(tempMap);
			
			result.put("objList", objList);
			
//			result.put("menuList", menuList);
//			result = this.returnPage(result, page);
		}
		
		ResponseUtil.writeJson(result, response);

	}
	
	/**
	 * 添加处理
	 * @param menu
	 * @param response
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public void add(@RequestBody Menu obj, HttpServletRequest request, HttpServletResponse response){
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				this.init(obj);
				
				menuService.add(obj);
				
//				for(int i =0;i<list.size();i++){
//					MenuRoleUser menuRoleUser = list.get(i);
//					MenuRole menuRole = new MenuRole();
//					menuRole.setStrCarrierId(menuRoleUser.getId());
//					menuRole.setStrCarrierType(menuRoleUser.getType());
//					menuRole.setStrMenuId(obj.getStrId());
//					menuRoleService.add(menuRole);
//				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
			}
		}
		ResponseUtil.writeJson(result, response);
		
	}
	
	/**
	 * 修改处理
	 * @param menu
	 * @param response
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public void update(@RequestBody Menu obj, HttpServletRequest request, HttpServletResponse response){
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
	//			List<String> childIds = menuService.listIdsByParentId(obj.getStrId());
	//			//新父节点不能为其自身以及其子节点
	//			if(obj.getStrId().equals(obj.getStrParentId()) || childIds.contains(obj.getStrParentId())){
	//				result.setCode(1);
	//				result.setMessage("-1");
	//			}else{
					obj.setDtUpdateDate(new Date());
					menuService.update(obj);
	//			}
				
//				for(int i =0;i<list.size();i++){
//					MenuRoleUser menuRoleUser = list.get(i);
//					MenuRole menuRole = new MenuRole();
//					menuRole.setStrCarrierId(menuRoleUser.getId());
//					menuRole.setStrCarrierType(menuRoleUser.getType());
//					menuRole.setStrMenuId(obj.getStrId());
//					menuRoleService.add(menuRole);
//				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
			}
		}
		ResponseUtil.writeJson(result, response);
	}


	/**
	 * 删除处理
	 * @param paramModel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public void delete(@RequestBody ParamModel paramModel,HttpServletRequest request, HttpServletResponse response){
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = paramModel.getStrId();
				menuService.deleteAll(strId);		//删除其自身及其子集
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/view")
	public void view(@RequestBody ParamModel paramModel,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = paramModel.getStrId();
				Menu obj = menuService.findById(strId);
				result.put("obj", obj);
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	private List<Map<String,Object>> creatJsonTree(List<Menu> menuList){
		List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>();
		if(menuList != null){
			for(Menu obj: menuList){
				Map<String,Object> tempMap = new HashMap<String,Object>();
				
				tempMap.put("strParentNodeId", obj.getStrId());
				tempMap.put("strParentNodeName", obj.getStrName());
				tempMap.put("strTitle", obj.getStrTitle());
				tempMap.put("strIcon", obj.getStrIcon());
				tempMap.put("strRoute", obj.getStrRoute());
				tempMap.put("strUrl", obj.getStrUrl());
				tempMap.put("dtCreatDate", obj.getDtCreatDate());
				tempMap.put("dtUpdateDate", obj.getDtUpdateDate());
				tempMap.put("strState", obj.getStrState());
				List<Map<String,Object>> tempJson = creatJsonTree(obj.getChildren());
				if(tempJson!=null && tempJson.size()>0){
					tempMap.put("children", tempJson);
				}
				tempMap.put("expand", false);
				tempList.add(tempMap);
			}
		}
		return tempList;
	}
	
	private List<Menu> creatMenuTree(List<Menu> menuList,Map<String, List<Menu>> menuListMap){
		List<Menu> list=null;
		for(int i=0;menuList!=null&&i<menuList.size();i++){
			Menu obj=menuList.get(i);
			list=list==null?new ArrayList<Menu>():list;
			obj.setChildren(creatMenuTree(menuListMap.get(obj.getStrId()),menuListMap));
				
			list.add(obj);
		}
		return list;
	}
}
